package vn.edu.hungvuongaptech.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import vn.edu.hungvuongaptech.common.Constant;
import vn.edu.hungvuongaptech.dao.RoleDAO;
import vn.edu.hungvuongaptech.dao.UserDAO;
import vn.edu.hungvuongaptech.model.RoleModel;
import vn.edu.hungvuongaptech.model.UserModel;

/**
 * LoginAction.
 * @author ThanhHQ
 *
 */
public class LoginController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, 
	 * javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, 
	 * javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("txtUsername");
		String password = request.getParameter("txtPassword");
		UserModel userModel = UserDAO.checkUser(username, password);
		RoleModel roleModel = new RoleModel();
		if (userModel != null) {
			roleModel = RoleDAO.getRoleModelById(userModel.getRoleId());
			HttpSession session = request.getSession(true);
			session.setAttribute(Constant.USERID_ATT, userModel.getUserId());
			session.setAttribute(Constant.USERNAME_ATT, userModel.getUsername());
			session.setAttribute(Constant.ROLE_ATT, userModel.getRoleId());
			session.setAttribute(Constant.ROLE_NAME_ATT, roleModel.getRoleName());
			String nextPath = "";
			switch (userModel.getRoleId()) {
			case 1: // Staff role.
				nextPath = Constant.PATH_RES.getString("timesheet.staff.listTimeSheetPath");
				break;
			case 2: // PM role.
				nextPath = Constant.PATH_RES.getString("timesheet.manager.listTimeSheetPath");
				break;
			case 3: // QA role
				nextPath = Constant.PATH_RES.getString("timesheet.admin.approvalPath");
				break;
			default:
				nextPath = Constant.PATH_RES.getString("timesheet.loginPath");
				break;
			}
			response.sendRedirect(nextPath);
		} else {
			response.sendRedirect(Constant.PATH_RES
					.getString("timesheet.loginPath")
					+ "?msg=Invalid username or password!");
		}
	}
}
